package com.hxkj.service.taglib.impl;

import com.alibaba.fastjson.JSONObject;
import com.hxkj.client.service.AnalyzeChannelServiceClient;
import com.hxkj.client.service.ChannelServiceClient;
import com.hxkj.client.service.GeneratorStaticFileServiceClient;
import com.hxkj.domain.enums.ChannelExceptionEnum;
import com.hxkj.domain.po.Channel;
import com.hxkj.domain.po.FreeMarker;
import com.hxkj.service.taglib.AnalyzeChannelService;
import com.platform.common.domain.exception.CustomException;
import com.platform.common.domain.exception.CustomMessageException;
import com.platform.common.domain.result.ResultDataStruct;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static com.hxkj.domain.Constant.CmsConstants.CHANNEL;

/**
 * @ClassName AnalyzeColumnServiceImpl
 * @Description TODO
 * @Author Mr.zheng
 * @Date 2018/7/18 17:41
 * @Version 1.0
 */
@Service
@Slf4j
public class AnalyzeChannelServiceImpl implements AnalyzeChannelService {

    @Autowired
    private AnalyzeChannelServiceClient analyzeChannelServiceClient;

    @Autowired
    private ChannelServiceClient channelServiceClient;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 频道静态文件生成
     * @param freeMarker
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject analyzeChannel(FreeMarker freeMarker) throws Exception {
        if (freeMarker.getChannelId() == null) {
            throw new CustomException(ChannelExceptionEnum.CHANNEL_NOT_EXIST);
        }
        if (freeMarker.getSiteId() == null) {
            throw new CustomException(ChannelExceptionEnum.CHANNEL_NOT_SITEID);
        }
        Channel channel = new Channel();
        channel.setChannelId(Long.valueOf(freeMarker.getChannelId()));
        channel.setSiteId(freeMarker.getSiteId());
        //生成频道静态文件时根据传入的频道ID来获取频道信息
        ResultDataStruct<Channel> channelResult = channelServiceClient.getChannel(channel);
        if (channelResult.getCode() != 200) {
            throw new CustomMessageException(channelResult.getCode(), channelResult.getMessage());
        }
        channel = channelResult.getData();
        if (channel.getTempletId() == null) {
            throw new CustomException(ChannelExceptionEnum.CHANNEL_TEMPLETID_NOT_EXIST);
        }
        if (channel.getTempletName() == null) {
            throw new CustomException(ChannelExceptionEnum.CHANNEL_TEMPLETNAME_NOT_EXIST);
        }
        freeMarker.setTempletId(channel.getTempletId());
        freeMarker.setWapTempletId(channel.getmTempletId());
        freeMarker.setAliasName(channel.getTempletName());
        freeMarker.setTime(channel.getCreateTime());
        //1标识频道解析
        freeMarker.setStatus(CHANNEL);
        ResultDataStruct analyzeResult = analyzeChannelServiceClient.analyzeChannel(freeMarker);
        if (analyzeResult.getCode() != 200) {
            throw new CustomMessageException(analyzeResult.getCode(),analyzeResult.getMessage());
        }
        return (JSONObject) analyzeResult.getData();
    }

    /**
     * 频道可视化
     * @param freeMarker
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject visualizationChannel(FreeMarker freeMarker) throws Exception {
        Channel channel = new Channel();
        channel.setSiteId(freeMarker.getSiteId());
        //模板可视化时因为是先选择的的模板,且生成临时静态文件不需要区分目录,所以不用管是pc端模板还是wap端模板
        channel.setTempletId(freeMarker.getTempletId());
        // 频道模板可视化时任取一条使用该模板的频道信息
        ResultDataStruct<Channel> chanelResult = channelServiceClient.getChannelByTempletId(channel);
        if (chanelResult.getCode() != 200) {
            throw new CustomMessageException(chanelResult.getCode(), chanelResult.getMessage());
        }
        channel = chanelResult.getData();
        freeMarker.setChannelId(String.valueOf(channel.getChannelId()));
        if (channel.getTempletName() == null) {
            throw new CustomException(ChannelExceptionEnum.CHANNEL_TEMPLETNAME_NOT_EXIST);
        }
        freeMarker.setAliasName(channel.getTempletName());
        freeMarker.setChannelId(channel.getChannelId().toString());
        //1标识频道解析
        freeMarker.setStatus(CHANNEL);
        ResultDataStruct analyzeResult = analyzeChannelServiceClient.analyzeChannel(freeMarker);
        if (analyzeResult.getCode() != 200) {
            throw new CustomMessageException(analyzeResult.getCode(),analyzeResult.getMessage());
        }
        return (JSONObject) analyzeResult.getData();
    }

    @Autowired
    private GeneratorStaticFileServiceClient generatorStaticFileServiceClient;

    /**
     * 多个频道生成静态页  chenfangzhou
     *
     * @param freeMarker
     * @throws Exception
     */
    @Override
    public void createChannelPages(FreeMarker freeMarker) throws Exception {
        List<Channel> list = new ArrayList<>();
        String websocket_key = "WEBSOCKET_KEY_" + UUID.randomUUID();
        // 如果传入了选中的频道列表,解析频道id并查询频道信息
        if(StringUtils.isNotBlank(freeMarker.getChannelIds())) {
            for (String channelId : freeMarker.getChannelIds().split(",")) {
                Channel channel = new Channel();
                channel.setChannelId(Long.valueOf(channelId));
                channel.setSiteId(freeMarker.getSiteId());
                Channel data = channelServiceClient.getChannel(channel).getData();
                data.setSocketKey(websocket_key);
                list.add(data);
            }
        }else{
            //没有传入频道的channelIds ,生成全部频道
            Channel channel = new Channel();
            channel.setSiteId(freeMarker.getSiteId());
            ResultDataStruct<List<Channel>> channelsResult = channelServiceClient.getListBySiteId(channel);
            if(channelsResult.getCode() != 200){
                throw new CustomMessageException(channelsResult.getCode(),channelsResult.getMessage());
            }
            List<Channel> channels = channelsResult.getData();
            if (channels == null || channels.size() == 0) {
                return;
            }
            String channelStr = "";
            for (Channel channel_ : channels) {
                channelStr += channel_.getChannelId() + ",";
            }
            String channelIds = channelStr.substring(0, channelStr.length() - 1);
            freeMarker.setChannelIds(channelIds);
        }

        if (list != null && list.size() != 0) {
            redisTemplate.opsForValue().set(websocket_key, 0);
            generatorStaticFileServiceClient.GenChannelFile(list);
        }
    }
}
